import axios from "axios";
import { loadingBar, message } from 'heyui';
import useStore from '@/store/index';
const instance = axios.create({
  timeout: 60000,
});

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    const url = config.url;
    if (url.startsWith("/system")) {
      config.baseURL = "/";
    } else {
      config.baseURL = "/ollama/";
    }
    loadingBar.start();
    return config;
  },
  (error) => {
    loadingBar.fail();
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res)
      if (response.data.code == 401) {
        message.error("登录已过期");
        loadingBar.fail();
      } else if (response.data.code == 404) {
        message.error("请求地址无效");
        loadingBar.fail();
      } else if (response.data.code != undefined && response.data.code != 200) {
        message.error(response.data.msg);
        loadingBar.fail();
      } else {
        loadingBar.success();
      }
    return response;
  },
  (error) => {
    loadingBar.fail();
    if (error.response.status === 401) {
      const store = useStore();
      store.setLoginFlag(false);
    }
    return Promise.reject(error);
  }
);

export default instance;
